package com.bbs.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.bbs.dao.PostDao;
import com.bbs.model.Posts;

public class PosterDaoImpl implements PostDao {

	private Connection conn = null;
	private PreparedStatement pstm = null;
	private ResultSet rs = null;

	/**
	 * 数据库连接
	 * 
	 * @return Connection
	 */
	private Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
					"jdbc:mysql://127.0.0.1:3306/bbs", "root", "42154234");

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭ResultSet PreparedStatement Connection
	 * 
	 * @return true成功关闭，false关闭失败
	 * @throws SQLException
	 */
	private boolean getClose() throws SQLException {
		if (rs != null) {
			rs.close();
		}
		if (pstm != null) {
			pstm.close();
		}
		if (conn != null) {
			conn.close();
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.bbs.dao.PostDao#searchPostsById(int)
	 */
	@Override
	public Posts searchPostsById(int postsId) throws SQLException {
		if (conn == null) {
			conn = getConnection();
		}
		String sql = "select id, author, title, kind, content, time, visits, downloadCount, digest " +
				"from posts where id = ?";
		pstm = conn.prepareStatement(sql);
		pstm.setInt(1, postsId);
		rs = pstm.executeQuery();
		Posts posts = new Posts();
		if(rs.next()) {
			posts.setAuthor(rs.getString("author"));
			posts.setContent(rs.getString("content"));
			posts.setDigest(rs.getInt("digest"));
			posts.setDownloadCount(rs.getInt("downloadCount"));
			posts.setId(rs.getInt("id"));
			posts.setKind(rs.getString("kind"));
			posts.setTime(new Date(rs.getTimestamp("time").getTime()));
			posts.setTitle(rs.getString("title"));
			posts.setVisits(rs.getInt("visits"));
		}
		return null;
	}

}
